package org.jsola.hr.service.impl;

import com.alibaba.excel.EasyExcel;
import jodd.util.StringUtil;
import org.jsola.common.DateKit8;
import org.jsola.core.Page;
import org.jsola.hr.common.DateUtils;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ISaleServerCostRecordDAO;
import org.jsola.hr.dto.SaleServerCostRecordAddDTO;
import org.jsola.hr.dto.SaleServerCostRecordImportDTO;
import org.jsola.hr.dto.SaleServerCostRecordUpdateDTO;
import org.jsola.hr.dto.excel.EmpChangeImportDTO;
import org.jsola.hr.entity.SaleServerCostRecordDO;
import org.jsola.hr.query.SaleServerCostRecordQuery;
import org.jsola.hr.service.ISaleServerCostRecordService;
import org.jsola.hr.service.excel.SaleServerCostRecordListener;
import org.jsola.hr.vo.ImportExcelResultListVO;
import org.jsola.hr.vo.SaleServerCostRecordListVO;
import org.jsola.hr.vo.SaleServerCostRecordVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 客户服务费记录
 *
 * @author zhr
 */
@Service("hrSaleServerCostRecordServiceImpl")
public class SaleServerCostRecordServiceImpl implements ISaleServerCostRecordService {

    @Autowired
    private ISaleServerCostRecordDAO saleServerCostRecordDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SaleServerCostRecordVO save(SaleServerCostRecordAddDTO saleServerCostRecordAddDTO, TokenUser tokenUser) {
        // 转DO
        SaleServerCostRecordDO saleServerCostRecordDO = saleServerCostRecordAddDTO.to(SaleServerCostRecordDO.class);
        // 保存
        saleServerCostRecordDO = save(saleServerCostRecordDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return saleServerCostRecordDO.to(SaleServerCostRecordVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SaleServerCostRecordUpdateDTO saleServerCostRecordUpdateDTO, TokenUser tokenUser) {
        //转DO
        SaleServerCostRecordDO saleServerCostRecordDO = saleServerCostRecordUpdateDTO.to(SaleServerCostRecordDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(saleServerCostRecordDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... saleServerCostRecordIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) saleServerCostRecordIds);
    }


    @Override
    public SaleServerCostRecordVO selectById(String saleServerCostRecordId, String siteId) {
        SaleServerCostRecordDO saleServerCostRecordDO = selectDOById(saleServerCostRecordId, siteId);
        if (saleServerCostRecordDO == null) {
            return null;
        }
        return saleServerCostRecordDO.to(SaleServerCostRecordVO.class);
    }

    @Override
    public List<SaleServerCostRecordListVO> select(SaleServerCostRecordQuery saleServerCostRecordQuery, String siteId) {
        List<SaleServerCostRecordDO> saleServerCostRecordDOList = selectDO(saleServerCostRecordQuery, siteId);
        if (CollectionUtils.isEmpty(saleServerCostRecordDOList)) {
            return saleServerCostRecordDOList == null ? null : new ArrayList<>();
        }
        return saleServerCostRecordDOList.stream()
                .map(saleServerCostRecordDO -> saleServerCostRecordDO.to(SaleServerCostRecordListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SaleServerCostRecordQuery saleServerCostRecordQuery, String siteId) {
        Example example = buildExample(saleServerCostRecordQuery, siteId);
        return saleServerCostRecordDAO.selectCountByExample(example);
    }

    @Override
    public Page<SaleServerCostRecordListVO> selectPage(SaleServerCostRecordQuery saleServerCostRecordQuery, String siteId) {
        Example example = buildExample(saleServerCostRecordQuery, siteId);
        Page<SaleServerCostRecordDO> page = saleServerCostRecordDAO.selectPageByExample(example,
                saleServerCostRecordQuery.getPageNo(),
                saleServerCostRecordQuery.getPageSize());

        return page.to(SaleServerCostRecordListVO.class);
    }

    @Override
    public SaleServerCostRecordDO selectDOById(String saleServerCostRecordId, String siteId) {
        return listById(saleServerCostRecordId, siteId);
    }

    @Override
    public List<SaleServerCostRecordDO> selectDO(SaleServerCostRecordQuery saleServerCostRecordQuery, String siteId) {
        Example example = buildExample(saleServerCostRecordQuery, siteId);
        return saleServerCostRecordDAO.selectByExample(example);
    }

    @Override
    public ImportExcelResultListVO<SaleServerCostRecordImportDTO> importFile(File file, TokenUser tokenUser) {
        SaleServerCostRecordListener saleServerCostRecordListener = new SaleServerCostRecordListener();
        saleServerCostRecordListener.setTokenUser(tokenUser);
        EasyExcel.read(file, SaleServerCostRecordImportDTO.class, saleServerCostRecordListener).sheet().doRead();
        ImportExcelResultListVO<SaleServerCostRecordImportDTO> result = new ImportExcelResultListVO<>();
        List<SaleServerCostRecordImportDTO> failList = saleServerCostRecordListener.getFailList();
        for (SaleServerCostRecordImportDTO recordImport : failList) {
            recordImport.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
        }
        result.setErrorList(failList);
        result.setAllCount(saleServerCostRecordListener.getAllCount());
        result.setSuccessCount(saleServerCostRecordListener.getSuccessCount());
        result.setErrorCount(saleServerCostRecordListener.getFailCount());
        List<String> headList = new ArrayList<String>() {{
            add("错误信息");
            add("用工单位名称");
            add("年月");
            add("服务费金额");
        }};
        result.setHeadList(headList);
        return result;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void saveImportList(List<SaleServerCostRecordImportDTO> saveDataList, TokenUser tokenUser) {
        List<SaleServerCostRecordDO> saveList = new ArrayList<>();
        for (SaleServerCostRecordImportDTO importRecord : saveDataList) {
            SaleServerCostRecordDO toResult = importRecord.to(SaleServerCostRecordDO.class);
            toResult.preInsert(tokenUser.getUserId());
            toResult.setSiteId(tokenUser.getSiteId());
            saveList.add(toResult);
        }
        this.bachSave(saveList);
    }

    @Override
    public List<SaleServerCostRecordDO> selectCompanyRecordByMonth(String companyId, String costMonth, TokenUser tokenUser) {
        Example example = new Example(SaleServerCostRecordDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("costMonth", costMonth)
                .andEqualTo("companyId", companyId);
        return saleServerCostRecordDAO.selectByExample(example);
    }

    @Override
    public void bachSave(List<SaleServerCostRecordDO> saveList) {
        saleServerCostRecordDAO.insertListAndSetId(saveList);
    }

    @Override
    public void overlaidData(List<SaleServerCostRecordImportDTO> importDataList, TokenUser tokenUser) {
        for (SaleServerCostRecordImportDTO importData : importDataList) {
            // 先把那条重复的数据找出来
            List<SaleServerCostRecordDO> recordList = this
                    .selectCompanyRecordByMonth(importData.getCompanyId(), importData.getCostMonth(), tokenUser);
            if(CollectionUtils.isEmpty(recordList)){
                continue;
            }
            SaleServerCostRecordDO record = recordList.get(0);
            deleteByIds(tokenUser, record.getId());
            // 为了好追溯问题  把原来那个 删掉  再加一条新的
            SaleServerCostRecordAddDTO addDTO = new SaleServerCostRecordAddDTO();
            addDTO.setCompanyId(importData.getCompanyId());
            addDTO.setCompanyName(importData.getCompanyName());
            addDTO.setServerCost(new BigDecimal(importData.getServerCost()));
            addDTO.setCostMonth(importData.getCostMonth());
            addDTO.setRemark(DateKit8.format2Date(new Date()) + "覆盖原数据,原数据id为" + record.getId());
            this.save(addDTO, tokenUser);
        }
    }

    @Override
    public List<SaleServerCostRecordDO> selectCompanyRecord(String companyId, TokenUser tokenUser) {
        Example example = new Example(SaleServerCostRecordDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andEqualTo("companyId", companyId);
        return saleServerCostRecordDAO.selectByExample(example);
    }

    @Override
    public String exportErrorList(ImportExcelResultListVO<SaleServerCostRecordImportDTO> errorList) {
        return ExcelKit.exportExcel("saleServerCostRecordError", "错误列表",
                SaleServerCostRecordImportDTO.class, errorList.getErrorList());
    }

    /**
     * 根据查询参数，构建example
     *
     * @param saleServerCostRecordQuery 查询参数
     * @param siteId                    所属站点id
     * @return example
     */
    private Example buildExample(SaleServerCostRecordQuery saleServerCostRecordQuery, String siteId) {
        Example example = new Example(SaleServerCostRecordDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (!StringUtils.isEmpty(saleServerCostRecordQuery.getCompanyName())) {
            example.and().andLike("companyName", "%" + saleServerCostRecordQuery.getCompanyName() + "%");
        }
        if (!ObjectUtils.isEmpty(saleServerCostRecordQuery.getEndTime())) {
            example.and().andLessThanOrEqualTo("costMonth", saleServerCostRecordQuery.getEndTime());
        }
        if (!ObjectUtils.isEmpty(saleServerCostRecordQuery.getBeginTime())) {
            example.and().andGreaterThanOrEqualTo("costMonth", saleServerCostRecordQuery.getBeginTime());
        }
        // 排序
        ExampleKit.setExampleOrder(example, saleServerCostRecordQuery.getOrders());
        return example;
    }
}




